package com.example.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.example.config.AlipayConfig;
import com.example.pojo.Inputs;
import com.example.pojo.Sx;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/tools")
public class ToolsController {

    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    // 从环境变量或配置文件中获取AccessKey ID和AccessKey Secret
    private static final String accessKeyId = "LTAI5tN55tgyw956bJzemEZ6";
    private static final String accessKeySecret ="riKjI22au4JMf8R70QrxCfQDKdnGmk";

    @PostMapping("/oss")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws InterruptedException {
        // 处理上传的文件
        if (!file.isEmpty()) {
            Thread.sleep(10);
            long current_time_ep = Instant.now().toEpochMilli();
            // 可以根据需要保存文件到磁盘、存储到数据库或者进行其他处理
            // 填写Bucket名称，ethereal。
            String bucketName = "ethereal";
            // 填写Object完整路径，完整路径中不能包含Bucket名称，例如images/photo.jpg。
            //        String objectName = "images/test.png";
            //        String objectName = "video/test.mp4";
            //先获取文件名
            String fileName = file.getOriginalFilename();
            //后缀文件
            String fileExtension ="";
            int lastIndex = fileName != null ? fileName.lastIndexOf('.') : 0;

            String objectName = "";
            if (lastIndex > 0){
                fileExtension = fileName.substring(lastIndex);
            }
            if (fileExtension.equals(".png") || fileExtension.equals(".jpg")){
                 objectName = "images/"+current_time_ep+fileExtension;
            }else if(fileExtension.equals(".mp3")){
                 objectName = "music/"+current_time_ep+fileExtension;
            }else if(fileExtension.equals(".mp4")){
                objectName = "video/"+current_time_ep+fileExtension;
            }
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            URL url = null;
            try {
                // 创建PutObjectRequest对象，指定上传的OSS文件名和文件输入流。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

                //生成预签名
                // 计算一年后的时间
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.YEAR, 1);
                Date expiration = calendar.getTime();
                GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName,objectName);
                request.setExpiration(expiration);
                //生成预签名 url
                url = ossClient.generatePresignedUrl(request);
                //打印
                System.out.println("预签名："+url.toString());

                // 上传文件。
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                // 删除文件
                //ossClient.deleteObject(bucketName, objectName);
                // 打印上传结果。
                System.out.println("ETag: " + result.getETag());
                System.out.println("VersionId: " + result.getVersionId());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException:");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException:");
                System.out.println("Error Message:" + ce.getMessage());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }



            return url+"&&&"+objectName;
        } else {
            // 文件为空的处理逻辑，如果允许上传空文件需要处理这种情况
            return "文件为空";
        }
    }
    @GetMapping("ok")
    public String Ok(){
        return "ok";
    }


    @GetMapping("del")
    public String Del(@RequestParam("objectName") String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject("ethereal", objectName);
        return "ok";
    }

    @GetMapping("msg")
    public String xzs(@RequestParam("msg") String msg) {
        try {
            // 构建请求 URL
            String encodedMsg = URLEncoder.encode(msg, "UTF-8");
            String urlStr = "http://api.qingyunke.com/api.php" +
                    "?key=free" +
                    "&appid=0" +
                    "&msg=" + encodedMsg;

            // 创建 URL 对象
            URL url = new URL(urlStr);

            // 创建 HTTP 连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 发起请求
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应数据
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应结果
                System.out.println("API 返回的消息内容: " + response.toString());

                // 可以根据实际需求进一步处理返回的 JSON 数据，比如解析、存储等操作
                return response.toString();
            } else {
                System.out.println("HTTP 请求失败: " + responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 支付请求接口
     */
    @GetMapping("/pay") // 订单id（不能重复）和消费金额
    public void pay(@RequestParam("orderId") String orderId,@RequestParam("cost") String cost,@RequestParam("uid") Integer uid, HttpServletResponse response){
        try {
            AlipayClient alipayClient = AlipayConfig.getAlipayClient();
            // 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            AlipayTradePayModel model = new AlipayTradePayModel();
            // 设定订单号 必须要写,且订单号不能重复，目前已经只是做测试，已经写死
            model.setOutTradeNo(orderId);
            // 设置订单金额
            model.setTotalAmount(cost);
            // 订单名字
            model.setSubject("书籍订单");
            // 订单描述
            model.setBody("这是一本书籍的消费订单");
            // 产品码
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            // 设置参数
            alipayRequest.setBizModel(model);
            // 设置回调地址
            String url = "http://localhost:9527/userdetail.html?uid=" +uid;
            System.out.println(url);

            alipayRequest.setReturnUrl(url);
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 支付成功后，回调页面
     */
    @RequestMapping("success")
    public void success(@RequestParam("orderId") String orderId, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("订单Id为"+orderId+"的订单已经成功支付");
    }

    @Resource
    private RedisTemplate<String, List<Sx>> redisTemplate;

    @GetMapping("getSx")
    public List<Sx> getSx(@RequestParam("title") String  title) {
        // 首先尝试从 Redis 缓存中获取数据
        String cacheKey = "Sx:" + title;
        List<Sx> cachedUser = redisTemplate.opsForValue().get(cacheKey);

        if (cachedUser != null) {
            // 如果缓存中有数据，直接返回缓存数据
            return cachedUser;
        }

        // 如果缓存中没有数据，则从数据库中获取数据（这里的逻辑需要根据实际情况进行调整）
        List<Sx> userFromDB = new ArrayList<>();

        if (userFromDB != null) {
            // 将从数据库中获取的数据存入 Redis 缓存
            // 设置缓存时间为40天
            redisTemplate.opsForValue().set(cacheKey, userFromDB, 10, TimeUnit.DAYS);
            return userFromDB;
        } else {
            // 数据库中没有找到对应用户，返回空对象或者其他处理
            return new ArrayList<>(); // 返回空对象示例
        }
    }

    @GetMapping("makeSx")
    public String makeSx(@RequestParam("userid") String  userid,@RequestParam("title") String title,
                           @RequestParam("message") String message) {
        String cacheKey = "Sx:" + title;

        // 尝试从 Redis 缓存中获取数据
        List<Sx> cachedUser = redisTemplate.opsForValue().get(cacheKey);

        // 如果缓存中不存在用户的日期列表，则初始化一个新的列表
        if (cachedUser == null) {
            cachedUser = new ArrayList<>();
        }
//获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //格式转化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String nowdate = now.format(formatter);
        Sx sx = new Sx();
        sx.setUserid(userid);
        sx.setTitle(title);
        sx.setDate(nowdate);
        sx.setMessage(message);
        // 向用户的最后登录日期列表添加新的日期
        cachedUser.add(sx);
        // 设置缓存时间为40天
        redisTemplate.opsForValue().set(cacheKey, cachedUser, 10, TimeUnit.DAYS);

        return "ok";
    }


}